import React, { useState, useRef, useEffect } from 'react';
import ProForm, { ModalForm, ProFormText, ProFormRadio, ProFormTextArea, ProFormCheckbox } from '@ant-design/pro-form';
import { spShopInfo, getShopInfo } from '@/services/shop/api'
import RichText from '@/components/RichText'
import BraftEditor from 'braft-editor';
import { Form, Button, Badge } from 'antd';
import { isExits, showMsg, submitRichTextImgHost, replaceRichTextImgHost } from '@/utils/utils';
import Auditing from '@/components/Auditing';


interface ShopInfoProps {
  handleModalVisible: (visible: boolean) => void;
  handleAdd: (data: SHOPAPI.ShopInfo) => Promise<boolean>;
  tagList: MALLAPI.MallTag[];
  onSp: Function;
  curStatus: string;
}

const OptForm: React.FC<ShopInfoProps> = (props) => {
  const { 
    handleModalVisible, 
    handleAdd, 
    tagList,
    onSp,
  } = props;
  console.log(tagList)

  const [loading, setLoading] = useState<boolean>(false);
  const [shopInfo, setShopInfo] = useState<SHOPAPI.ShopInfo>({} as SHOPAPI.ShopInfo);

  const formRef = useRef();
  const auditingRef = useRef();
  
  const [editorState, setEditorState] = useState<any>(BraftEditor.createEditorState(''))

  const fetchShopInfo = async () => {
    try {
      const data: SHOPAPI.ShopInfo = await getShopInfo('E');
      setShopInfo(data);
      setEditorState(BraftEditor.createEditorState(replaceRichTextImgHost(data.shop_desc)))
      console.log('formRef.current', formRef.current)
      formRef.current.resetFields();
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  useEffect(() => {
    fetchShopInfo();
  }, [])



  const getStatus = (status: string) => {
    switch (status) {
      case 'W': return { status: 'warning', text: '待审批' }
      case 'N': return { status: 'processing', text: '已发布' }
      case 'D': return { status: 'error', text: '已拒绝' }
      case 'C': return { status: 'success', text: '草稿' }
    }
  }

  const onFinish = async(value, status) => {
    console.log(value)
    value = Object.assign({}, value, { shop_desc: submitRichTextImgHost(editorState.toHTML()), approval_status: status})
    if (loading) {
      return;
    }
    setLoading(true);
    const success = await handleAdd(value as SHOPAPI.ShopInfo);
    if (success) {
      handleModalVisible(false);
    }
    setLoading(false);
  }

  const sp = async (status) => {
    setLoading(true);
    const data = { approval_id: shopInfo.approval_id, status };
    auditingRef?.current?.onSign({sign_no: shopInfo.approval_id, sign_string: JSON.stringify(data), title: `小程序店铺信息审批`}, async() => {
      await spShopInfo(data).then(res => {
        setLoading(false);
        showMsg(status === 'N' ? '已通过审批' :'已拒绝审批', 'success');
        onSp();
      }).catch((error) => {
        setLoading(false);
        showMsg(error?.data?.errmsg);
      })
    });
  }

  const statusObj = getStatus(shopInfo.approval_status);


  return <ModalForm
      className="shop-info-modal-form"
      title="编辑店铺信息"
      width="90%"
      layout="horizontal"
      visible
      formRef={formRef}
      modalProps={{
        maskClosable: false,
      }}
      onVisibleChange={handleModalVisible}
      onFinish={v => onFinish(v, 'C')}
      submitter={{
        searchConfig: {
          resetText: '取消',
          submitText: '保存'
        },
        submitButtonProps: {
          loading,
          disabled: shopInfo.approval_status === 'W',
        },
        render: (props, dom) => {
          return <div style={{ display: 'inline-flex', alignItems: 'center' }}>
            {dom}
            {shopInfo.approval_status === 'C' && <Button loading={loading} type='primary' onClick={() => onFinish(formRef?.current?.getFieldsValue(), 'W')}>提交审批</Button>}
            {
              (shopInfo.approval_status === 'W' && isExits('600601004')) &&
              <>
                <Auditing
                  ref={auditingRef}
                  loading={loading}
                  module='S'
                  onLoading={e => setLoading(e)}
                  onError={() => {
                    setLoading(false);
                  }}
                  onClick={() => sp('N')}
                  _html={<Button style={{ marginLeft: 8 }} loading={loading} type='primary'>审批发布</Button>}
                />
                <Auditing
                  ref={auditingRef}
                  loading={loading}
                  module='S'
                  onLoading={e => setLoading(e)}
                  onError={() => {
                    setLoading(false);
                  }}
                  onClick={() => sp('D')}
                  _html={<Button style={{ marginLeft: 8 }} loading={loading} type='primary'>审批拒绝</Button>}
                />
              </>
            }
          </div>;
        }
      }}
      >
      <ProForm.Group>
        <div style={{ width: '88px', height: 26, textIndent: 12 }}>编辑状态：</div>
        <Badge text={statusObj?.text} status={statusObj?.status} />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="店铺名称"
          placeholder="请输入店铺名称"
          width="md"
          name="shop_name"
          initialValue={shopInfo.shop_name}
        />
      </ProForm.Group>

      <ProForm.Group>
        <Form.Item required label="店铺介绍">
          <RichText setEditorState={setEditorState} editorState={editorState}/>
        </Form.Item>
      </ProForm.Group>

      <ProForm.Group>
        <ProFormCheckbox.Group
          label="启用模块"
          name="tag_ids" 
          initialValue={shopInfo.tag_ids}
          rules={
            [
              {
                required: true
              }
            ]
          }
          options={tagList.map(item => {
            return {
              label: item.tag_name as string,
              value: item.tag_id as string
            }
          })} />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormText
            rules={
              [
                {
                  required: true
                }
              ]
            }
            label="提货地址"
            placeholder="请输入患者自提商品的提货地址"
            width="lg" 
            name="take_address" 
            initialValue={shopInfo.take_address}
          />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormText
            rules={
              [
                {
                  required: true
                }
              ]
            }
            label="退货寄回联系人"
            placeholder="请输入退货寄回联系人"
            width="md" 
            name="refund_liaison_person" 
            initialValue={shopInfo.refund_liaison_person}
          />
          <ProFormText
            label="电话"
            rules={
              [
                {
                  required: true
                }
              ]
            }
            labelCol={{ span: 3 }}
            placeholder="请输入联系人电话"
            width="md" 
            name="refund_liaison_mobile" 
            initialValue={shopInfo.refund_liaison_mobile}
          />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormText
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="退货寄回地址"
          placeholder="请输入退货寄回地址"
          width="lg" 
          name="refund_address" 
          initialValue={shopInfo.refund_address}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormText
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="退货送回地址"
          placeholder="请输入退货送回地址"
          width="lg" 
          name="refund_self_address" 
          initialValue={shopInfo.refund_self_address}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormRadio.Group
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="店铺状态"
          width="md"
          name="shop_status"
          initialValue={shopInfo.shop_status}
          options={[
            {
              label: '已开店',
              value: 'O'
            },
            {
              label: '已闭店',
              value: 'C'
            }
          ]}
          />
      </ProForm.Group>
    </ModalForm>
}
export default OptForm;
